<template>
  <div class="behavior-orchestration-designer">
    <div class="designer-header">
      <h3>行为编排设计器</h3>
      <div class="header-actions">
        <a-button @click="saveOrchestration" type="primary">
          <template #icon>
            <IconifyIcon icon="ant-design:save-outlined" />
          </template>
          保存编排
        </a-button>
        <a-button @click="validateOrchestration" type="default">
          <template #icon>
            <IconifyIcon icon="ant-design:check-circle-outlined" />
          </template>
          验证流程
        </a-button>
        <a-button @click="testOrchestration" type="default">
          <template #icon>
            <IconifyIcon icon="ant-design:play-circle-outlined" />
          </template>
          测试执行
        </a-button>
        <a-button @click="exportOrchestration" type="default">
          <template #icon>
            <IconifyIcon icon="ant-design:export-outlined" />
          </template>
          导出
        </a-button>
        <GuideWrapper guide-type="data-reference" title="数据引用使用指南" />
      </div>
    </div>

    <div class="designer-content">
      <div
        ref="tinyflowContainer"
        class="behavior-workflow-canvas h-full w-full"
      ></div>
    </div>

    <!-- 测试抽屉 -->
    <a-drawer
      v-model:open="testDrawerVisible"
      title="编排流程测试"
      width="600px"
      placement="right"
    >
      <div class="test-content">
        <div class="test-section">
          <h4>测试参数</h4>
          <div class="param-list">
            <div
              v-for="(param, index) in testParams"
              :key="index"
              class="param-item"
            >
              <a-input
                v-model:value="param.key"
                placeholder="参数名"
                class="param-key"
              />
              <a-input
                v-model:value="param.value"
                placeholder="参数值"
                class="param-value"
              />
              <a-button
                type="text"
                danger
                @click="removeTestParam(index)"
                class="param-remove"
              >
                <template #icon>
                  <IconifyIcon icon="ant-design:delete-outlined" />
                </template>
              </a-button>
            </div>
          </div>
          <a-button type="dashed" @click="addTestParam" class="add-param-btn">
            <template #icon>
              <IconifyIcon icon="ant-design:plus-outlined" />
            </template>
            添加参数
          </a-button>
        </div>

        <div class="test-section">
          <h4>执行结果</h4>
          <div class="result-content">
            <div v-if="testLoading" class="loading">
              <IconifyIcon icon="ant-design:loading-outlined" spin />
              执行中...
            </div>
            <div v-else-if="testError" class="error">
              {{ testError }}
            </div>
            <pre v-else-if="testResult" class="result-json">
              {{ JSON.stringify(testResult, null, 2) }}
            </pre>
            <div v-else class="no-result">点击运行查看结果</div>
          </div>
        </div>

        <a-button
          type="primary"
          size="large"
          :loading="testLoading"
          @click="executeWorkflow"
          class="execute-btn"
        >
          执行编排
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { Tinyflow } from '@tinyflow-ai/ui';
import '@tinyflow-ai/ui/dist/index.css';
import { GuideWrapper } from '../../guides';

// Props
interface Props {
  orchestrationId?: string;
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'orchestration-saved': [orchestration: any];
  'orchestration-tested': [result: any];
}>();

// 响应式数据
const tinyflowContainer = ref<HTMLElement>();
let tinyflowInstance: any = null;tinyflowInstancetinyflowInstance
const workflowData = ref({
  nodes: [],
  edges: [],
  viewport: { x: 0, y: 0, zoom: 1 },
});

// 测试相关
const testDrawerVisible = ref(false);
const testParams = ref<Array<{ key: string; value: string }>>([]);
const testLoading = ref(false);
const testResult = ref<any>(null);
const testError = ref('');

// 资源数据引用配置
const resourceDataReferences = {
  // 资源属性引用
  properties: {
    label: '资源属性',
    icon: 'ant-design:setting-outlined',
    items: [
      { value: 'resource.name',label: '资源名称',type: 'string' },
      { value: 'resource.type',label: '资源类型',type: 'string' },
      { value: 'resource.status',label: '资源状态',type: 'string' },
      { value: 'resource.createdAt',label: '创建时间',type: 'datetime' },
      { value: 'resource.updatedAt',label: '更新时间',type: 'datetime' },
      { value: 'resource.owner',label: '资源所有者',type: 'string' },
      { value: 'resource.tags',label: '资源标签',type: 'array' },
      { value: 'resource.metadata',label: '元数据',type: 'object' },
    ],
  },
  // 资源状态引用
  status: {
    label: '资源状态',
    icon: 'ant-design:check-circle-outlined',
    items: [
      { value: 'status.lifecycle',label: '生命周期状态',type: 'string' },
      { value: 'status.availability',label: '可用性状态',type: 'string' },
      { value: 'status.version',label: '版本状态',type: 'string' },
      { value: 'status.custom',label: '自定义状态',type: 'string' },
      { value: 'status.lastChange',label: '最后状态变更',type: 'datetime' },
      { value: 'status.changeReason',label: '状态变更原因',type: 'string' },
    ],
  },
  // 行为数据引用
  behavior: {
    label: '行为数据',
    icon: 'ant-design:code-outlined',
    items: [
      { value: 'behavior.current',label: '当前行为',type: 'string' },
      { value: 'behavior.history',label: '行为历史',type: 'array' },
      { value: 'behavior.executionCount',label: '执行次数',type: 'number' },
      {
        value: 'behavior.lastExecution',
        label: '最后执行时间',
        type: 'datetime',
      },
      { value: 'behavior.successRate',label: '成功率',type: 'number' },
    ],
  },
  // 事件数据引用
  events: {
    label: '事件数据',
    icon: 'ant-design:notification-outlined',
    items: [
      { value: 'events.recent',label: '最近事件',type: 'array' },
      { value: 'events.count',label: '事件总数',type: 'number' },
      { value: 'events.lastEvent',label: '最后事件',type: 'object' },
      { value: 'events.eventTypes',label: '事件类型',type: 'array' },
    ],
  },
  // 系统数据引用
  system: {
    label: '系统数据',
    icon: 'ant-design:computer-outlined',
    items: [
      { value: 'system.currentTime',label: '当前时间',type: 'datetime' },
      { value: 'system.user',label: '当前用户',type: 'string' },
      { value: 'system.tenant',label: '租户信息',type: 'string' },
      { value: 'system.environment',label: '运行环境',type: 'string' },
    ],
  },
};

// 行为编排 Provider - 提供节点类型
const behaviorProvider = {
  // 内部节点类型
  internal: () => [
    {
      value: 'start_node',
      label: '开始节点',
      icon: 'ant-design:play-circle-outlined',
    },
    {
      value: 'behavior_node',
      label: '行为执行',
      icon: 'ant-design:code-outlined',
    },
    {
      value: 'condition_node',
      label: '条件判断',
      icon: 'ant-design:branches-outlined',
    },
    {
      value: 'parallel_node',
      label: '并行执行',
      icon: 'ant-design:cluster-outlined',
    },
    {
      value: 'event_node',
      label: '事件节点',
      icon: 'ant-design:notification-outlined',
    },
    {
      value: 'delay_node',
      label: '延时等待',
      icon: 'ant-design:clock-circle-outlined',
    },
    {
      value: 'end_node',
      label: '结束节点',
      icon: 'ant-design:stop-outlined',
    },
  ],
  // 知识库节点类型;
  knowledge: () => [
    {
      value: 'data_query',
      label: '数据查询',
      icon: 'ant-design:search-outlined',
    },
    {
      value: 'data_update',
      label: '数据更新',
      icon: 'ant-design:edit-outlined',
    },
  ],
  // LLM节点类型;
  llm: () => [
    {
      value: 'llm_process',
      label: '智能处理',
      icon: 'ant-design:bulb-outlined',
    },
    {
      value: 'llm_analyze',
      label: '智能分析',
      icon: 'ant-design:fund-outlined',
    },
  ],
};

// 创建数据引用选择器组件
const createDataReferenceSelector = (
  parent: HTMLElement,
  flowInstance: any,
  node: any,
  fieldName: string,
) => {
  const container = document.createElement('div');
  container.className = 'data-reference-selector';
  container.style.cssText = `
    position: relative;positionposition
    display: flex;display
    align-items: center;
    gap: 4px;
  `;

  const input = document.createElement('input');
  input.type = 'text';
  input.placeholder = '选择数据引用或输入固定值';
  input.style.cssText = `
    flex: 1;flexflex
    padding: 4px 8px;padding
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    font-size: 12px;
  `;

  const selectBtn = document.createElement('button');
  selectBtn.innerHTML = '📊';
  selectBtn.title = '选择数据引用';
  selectBtn.style.cssText = `
    padding: 4px 8px;paddingpadding
    border: 1px solid #d9d9d9;border
    border-radius: 4px;
    background: #fff;
    cursor: pointer;
    font-size: 12px;
  `;

  // 创建数据引用选择弹窗
  const createReferenceModal = () => {
    const modal = document.createElement('div');
    modal.style.cssText = `
      position: fixed;positionposition
      top: 0;top
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    `;

    const content = document.createElement('div');
    content.style.cssText = `
      background: white;backgroundbackground
      border-radius: 8px;border-radius
      padding: 16px;
      max-width: 500px;
      max-height: 400px;
      overflow-y: auto;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    `;

    const header = document.createElement('div');
    header.innerHTML = '<h3 style="margin: 0 0 16px 0;">选择数据引用</h3>';

    const categories = document.createElement('div');
    categories.style.cssText =
      'display: flex; flex-direction: column; gap: 12px;';

    Object.entries(resourceDataReferences).forEach(([key, category]) => {
      const categoryDiv = document.createElement('div');
      categoryDiv.style.cssText =
        'border: 1px solid #f0f0f0; border-radius: 4px; padding: 8px;';

      const categoryHeader = document.createElement('div');
      categoryHeader.innerHTML = `<strong>${category.label}</strong>`;
      categoryHeader.style.cssText = 'margin-bottom: 8px; color: #1890ff;';

      const itemsDiv = document.createElement('div');
      itemsDiv.style.cssText =
        'display: flex; flex-direction: column; gap: 4px;';

      category.items.forEach((item) => {
        const itemBtn = document.createElement('button');
        itemBtn.textContent = `${item.label} (${item.value})`;
        itemBtn.style.cssText = `
          text-align: left;
          padding: 4px 8px;
          border: none;
          background: none;
          cursor: pointer;
          border-radius: 2px;
          font-size: 12px;
        `;

        itemBtn.onmouseover = () => {
          itemBtn.style.background = '#f5f5f5';
        };

        itemBtn.onmouseout = () => {
          itemBtn.style.background = 'none';
        };

        itemBtn.onclick = () => {
          input.value = `{{${item.value}}}`;
          modal.remove();
          updateNodeData();
        };

        itemsDiv.appendChild(itemBtn);
      });

      categoryDiv.appendChild(categoryHeader);
      categoryDiv.appendChild(itemsDiv);
      categories.appendChild(categoryDiv);
    });

    const closeBtn = document.createElement('button');
    closeBtn.textContent = '关闭';
    closeBtn.style.cssText = `
      margin-top: 16px;margin-topmargin-top
      padding: 8px 16px;padding
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      background: #fff;
      cursor: pointer;
    `;
    closeBtn.onclick = () => modal.remove();

    content.appendChild(header);
    content.appendChild(categories);
    content.appendChild(closeBtn);
    modal.appendChild(content);

    return modal;
  };

  const updateNodeData = () => {
    const currentData = flowInstance.getNodeData(node.id) || {};
    currentData[fieldName] = input.value;
    flowInstance.updateNodeData(node.id, currentData);
  };

  selectBtn.onclick = () => {
    const modal = createReferenceModal();
    document.body.appendChild(modal);
  };

  input.oninput = updateNodeData;

  container.appendChild(input);
  container.appendChild(selectBtn);
  return container;
};

// 行为编排自定义节点配置
const behaviorCustomNodes = {
  // 行为执行节点
  'behavior-execute': {
    title: '行为执行',
    description: '执行具体的行为操作',
    icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L2 7V10C2 16.0751 6.92487 21 13 21C19.0751 21 24 16.0751 24 10V7L14 2L12 2ZM12 4.23607L20 8.23607V10C20 14.4183 16.4183 18 12 18C7.58172 18 4 14.4183 4 10V8.23607L12 4.23607Z"></path></svg>',
    sortNo: 1,
    group: 'base',
    render: (parent: HTMLElement, node: any, flowInstance: any) => {
      parent.innerHTML = `
        <div style="padding: 8px;">
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;">行为类型:</label>
            <select style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
              <option value="CREATE">创建</option>
              <option value="UPDATE">更新</option>
              <option value="DELETE">删除</option>
              <option value="START">启动</option>
              <option value="STOP">停止</option>
              <option value="RESTART">重启</option>
              <option value="SCALE">扩缩容</option>
              <option value="MIGRATE">迁移</option>
              <option value="BACKUP">备份</option>
              <option value="RESTORE">恢复</option>
              <option value="DEPLOY">部署</option>
              <option value="ROLLBACK">回滚</option>
              <option value="CONFIGURE">配置</option>
              <option value="MONITOR">监控</option>
              <option value="NOTIFY">通知</option>
              <option value="CUSTOM">自定义</option>
            </select>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";<divstyle=<divstyle=<labelstyle=>目标资源:</label>
            <div id="target-resource-selector"></div>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";>执行参数:</label>
            <div id="execution-params-selector"></div>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";>超时时间:</label>
            <input type="number" min="1" max="3600" value="30" style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
          </div>
          <div>
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";>重试次数:</label>
            <input type="number" min="0" max="10" value="3" style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
          </div>
        </div>
      `;

      // 添加数据引用选择器
      const targetResourceSelector = parent.querySelector(
        '#target-resource-selector',
      );
      const executionParamsSelector = parent.querySelector(
        '#execution-params-selector',
      );

      if (targetResourceSelector) {
        const selector = createDataReferenceSelector(
          parent,
          flowInstance,
          node,
          'targetResource',
        );
        targetResourceSelector.appendChild(selector);
      }

      if (executionParamsSelector) {
        const selector = createDataReferenceSelector(
          parent,
          flowInstance,
          node,
          'executionParams',
        );
        executionParamsSelector.appendChild(selector);
      }

      const typeSelect = parent.querySelector('select');
      const timeoutInput = parent.querySelector(
        'input[type="number"]:first-of-type',
      ) as HTMLInputElement;
      const retryInput = parent.querySelector(
        'input[type="number"]:last-of-type',
      ) as HTMLInputElement;

      const updateData = () => {
        const currentData = flowInstance.getNodeData(node.id) || {};
        flowInstance.updateNodeData(node.id, {
          ...currentData,
          behaviorType: typeSelect?.value || 'CREATE',
          timeout: timeoutInput?.value || 30,
          retryCount: retryInput?.value || 3,
        });
      };

      typeSelect?.addEventListener('change', updateData);
      timeoutInput?.addEventListener('change', updateData);
      retryInput?.addEventListener('change', updateData);
    },
    onUpdate: (parent: HTMLElement, node: any) => {
      console.log('行为执行节点更新:', node);
    },
  },

  // 条件判断节点
  'condition-judge': {
    title: '条件判断',
    description: '根据条件进行分支判断',
    icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9V7L15 1H5C3.9 1 3 1.9 3 3V21C3 22.1 3.9 23 5 23H19C20.1 23 21 22.1 21 21V9ZM19 21H5V3H13V9H19V21Z"></path></svg>',
    sortNo: 2,
    group: 'base',
    render: (parent: HTMLElement, node: any, flowInstance: any) => {
      parent.innerHTML = `
        <div style="padding: 8px;">
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;">条件类型:</label>
            <select style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
              <option value="status">状态判断</option>
              <option value="value">数值比较</option>
              <option value="string">字符串匹配</option>
              <option value="custom">自定义条件</option>
            </select>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";<divstyle=<divstyle=<labelstyle=>左操作数:</label>
            <div id="left-operand-selector"></div>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";>比较操作:</label>
            <select style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
              <option value="eq">等于</option>
              <option value="ne">不等于</option>
              <option value="gt">大于</option>
              <option value="gte">大于等于</option>
              <option value="lt">小于</option>
              <option value="lte">小于等于</option>
              <option value="contains">包含</option>
              <option value="startsWith">开始于</option>
              <option value="endsWith">结束于</option>
            </select>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";>右操作数:</label>
            <div id="right-operand-selector"></div>
          </div>
        </div>
      `;

      // 添加数据引用选择器
      const leftOperandSelector = parent.querySelector(
        '#left-operand-selector',
      );
      const rightOperandSelector = parent.querySelector(
        '#right-operand-selector',
      );

      if (leftOperandSelector) {
        const selector = createDataReferenceSelector(
          parent,
          flowInstance,
          node,
          'leftOperand',
        );
        leftOperandSelector.appendChild(selector);
      }

      if (rightOperandSelector) {
        const selector = createDataReferenceSelector(
          parent,
          flowInstance,
          node,
          'rightOperand',
        );
        rightOperandSelector.appendChild(selector);
      }

      const typeSelect = parent.querySelector('select:first-of-type');
      const operatorSelect = parent.querySelector('select:last-of-type');

      const updateData = () => {
        const currentData = flowInstance.getNodeData(node.id) || {};
        flowInstance.updateNodeData(node.id, {
          ...currentData,
          conditionType: typeSelect?.value || 'status',
          operator: operatorSelect?.value || 'eq',
        });
      };

      typeSelect?.addEventListener('change', updateData);
      operatorSelect?.addEventListener('change', updateData);
    },
    onUpdate: (parent: HTMLElement, node: any) => {
      console.log('条件判断节点更新:', node);
    },
  },

  // 并行执行节点
  'parallel-execute': {
    title: '并行执行',
    description: '并行执行多个分支',
    icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L2 7V10C2 16.0751 6.92487 21 13 21C19.0751 21 24 16.0751 24 10V7L14 2L12 2ZM12 4.23607L20 8.23607V10C20 14.4183 16.4183 18 12 18C7.58172 18 4 14.4183 4 10V8.23607L12 4.23607Z"></path></svg>',
    sortNo: 3,
    group: 'base',
    render: (parent: HTMLElement, node: any, flowInstance: any) => {
      parent.innerHTML = `
        <div style="padding: 8px;">
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;">并行策略:</label>
            <select style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
              <option value="ALL">全部完成</option>
              <option value="ANY">任一完成</option>
              <option value="MAJORITY">多数完成</option>
            </select>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";<divstyle=<divstyle=<labelstyle=>超时处理:</label>
            <select style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
              <option value="CONTINUE">继续执行</option>
              <option value="FAIL">失败处理</option>
              <option value="CANCEL">取消执行</option>
            </select>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";>最大并发数:</label>
            <div id="max-concurrency-selector"></div>
          </div>
        </div>
      `;

      // 添加数据引用选择器
      const maxConcurrencySelector = parent.querySelector(
        '#max-concurrency-selector',
      );
      if (maxConcurrencySelector) {
        const selector = createDataReferenceSelector(
          parent,
          flowInstance,
          node,
          'maxConcurrency',
        );
        maxConcurrencySelector.appendChild(selector);
      }

      const strategySelect = parent.querySelector('select:first-of-type');
      const timeoutSelect = parent.querySelector('select:last-of-type');

      const updateData = () => {
        const currentData = flowInstance.getNodeData(node.id) || {};
        flowInstance.updateNodeData(node.id, {
          ...currentData,
          strategy: strategySelect?.value || 'ALL',
          timeoutAction: timeoutSelect?.value || 'CONTINUE',
        });
      };

      strategySelect?.addEventListener('change', updateData);
      timeoutSelect?.addEventListener('change', updateData);
    },
    onUpdate: (parent: HTMLElement, node: any) => {
      console.log('并行执行节点更新:', node);
    },
  },

  // 事件节点
  'event-trigger': {
    title: '事件触发',
    description: '触发或监听事件',
    icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2ZM21 9V7L15 1H5C3.9 1 3 1.9 3 3V21C3 22.1 3.9 23 5 23H19C20.1 23 21 22.1 21 21V9ZM19 21H5V3H13V9H19V21Z"></path></svg>',
    sortNo: 4,
    group: 'base',
    render: (parent: HTMLElement, node: any, flowInstance: any) => {
      parent.innerHTML = `
        <div style="padding: 8px;">
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;">事件类型:</label>
            <select style="width: 100%; padding: 4px; border: 1px solid #d9d9d9; border-radius: 4px;">
              <option value="TRIGGER">触发事件</option>
              <option value="LISTEN">监听事件</option>
              <option value="WAIT">等待事件</option>
            </select>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";<divstyle=<divstyle=<labelstyle=>事件名称:</label>
            <div id="event-name-selector"></div>
          </div>
          <div style="margin-bottom: 8px;">
            <label style="display: block; margin-bottom: 4px; font-weight: bold;";>事件数据:</label>
            <div id="event-data-selector"></div>
          </div>
        </div>
      `;

      // 添加数据引用选择器
      const eventNameSelector = parent.querySelector('#event-name-selector');
      const eventDataSelector = parent.querySelector('#event-data-selector');

      if (eventNameSelector) {
        const selector = createDataReferenceSelector(
          parent,
          flowInstance,
          node,
          'eventName',
        );
        eventNameSelector.appendChild(selector);
      }

      if (eventDataSelector) {
        const selector = createDataReferenceSelector(
          parent,
          flowInstance,
          node,
          'eventData',
        );
        eventDataSelector.appendChild(selector);
      }

      const typeSelect = parent.querySelector('select');

      const updateData = () => {
        const currentData = flowInstance.getNodeData(node.id) || {};
        flowInstance.updateNodeData(node.id, {
          ...currentData,
          eventType: typeSelect?.value || 'TRIGGER',
        });
      };

      typeSelect?.addEventListener('change', updateData);
    },
    onUpdate: (parent: HTMLElement, node: any) => {
      console.log('事件节点更新:', node);
    },
  },
};

// 初始化Tinyflow
onMounted(() => {
  if (tinyflowContainer.value) {
    console.log('初始化行为编排Tinyflow...');
    console.log('Behavior Provider配置:', behaviorProvider);
    console.log('Behavior Custom Nodes配置:', behaviorCustomNodes);

    try {
      // 检查是否已经存在Tinyflow实例
      if (tinyflowInstance) {
        tinyflowInstance.destroy();
        tinyflowInstance = null;
      }

      tinyflowInstance = new Tinyflow({
        element: tinyflowContainer.value,
        data: workflowData.value,
        provider: behaviorProvider,
        customNodes: behaviorCustomNodes,
      });

      console.log('Tinyflow实例:', tinyflowInstance);
    } catch (error) {
      console.error('Tinyflow初始化失败:', error);
      message.error('设计器初始化失败');
    }
  }
});

// 销毁Tinyflow
onUnmounted(() => {
  if (tinyflowInstance) {
    tinyflowInstance.destroy();
    tinyflowInstance = null;
  }
});

// 保存编排
const saveOrchestration = () => {
  try {
    const data = tinyflowInstance?.getData();
    if (data) {
      workflowData.value = data;
      console.log('保存编排:', data);

      const orchestration = {
        id: props.orchestrationId,
        resourceId: props.resourceId,
        resourceType: props.resourceType,
        workflow: data,
        status: 'ENABLED',
        createdAt: new Date().toISOString(),
      };

      message.success('编排保存成功');
      emit('orchestration-saved', orchestration);
    }
  } catch (error) {
    console.error('保存编排失败:', error);
    message.error('保存编排失败');
  }
};

// 验证编排
const validateOrchestration = () => {
  try {
    const data = tinyflowInstance?.getData();
    if (!data || !data.nodes || data.nodes.length === 0) {
      message.error('请先添加节点');
      return;
    }

    // 验证流程完整性
    const startNodes = data.nodes.filter(
      (node: any) => node.type === 'start_node',
    );
    const endNodes = data.nodes.filter((node: any) => node.type === 'end_node');

    if (startNodes.length === 0) {
      message.error('流程缺少开始节点');
      return;
    }

    if (endNodes.length === 0) {
      message.error('流程缺少结束节点');
      return;
    }

    if (startNodes.length > 1) {
      message.error('流程只能有一个开始节点');
      return;
    }

    message.success('流程验证通过');
  } catch (error) {
    console.error('验证编排失败:', error);
    message.error('验证编排失败');
  }
};

// 测试编排
const testOrchestration = () => {
  testDrawerVisible.value = true;
  testParams.value = [];
  testResult.value = null;
  testError.value = '';
};

// 导出编排
const exportOrchestration = () => {
  try {
    const data = tinyflowInstance?.getData();
    if (data) {
      const exportData = {
        orchestration: {
          id: props.orchestrationId,
          resourceId: props.resourceId,
          resourceType: props.resourceType,
          workflow: data,
        },
        exportTime: new Date().toISOString(),exportTimeexportTime
      };

      const dataStr = JSON.stringify(exportData, null, 2);
      const dataBlob = new Blob([dataStr], { type: 'application/json' });
      const url = URL.createObjectURL(dataBlob);

      const link = document.createElement('a');
      link.href = url;
      link.download = `behavior-orchestration_${props.orchestrationId || 'new'}.json`;
      link.click();

      URL.revokeObjectURL(url);
      message.success('编排导出成功');
    }
  } catch (error) {
    console.error('导出编排失败:', error);
    message.error('导出编排失败');
  }
};

// 添加测试参数
const addTestParam = () => {
  testParams.value.push({ key: '', value: '' });
};

// 移除测试参数
const removeTestParam = (index: number) => {
  testParams.value.splice(index, 1);
};

// 执行工作流
const executeWorkflow = async () => {
  try {
    testLoading.value = true;
    testError.value = '';
    testResult.value = null;

    const data = tinyflowInstance?.getData();
    if (!data || !data.nodes || data.nodes.length === 0) {
      throw new Error('请先设计编排流程');
    }

    // 构建测试参数
    const params: Record<string, any> = {};
    testParams.value.forEach((param) => {
      if (param.key.trim()) {
        params[param.key.trim()] = param.value;
      }
    });

    // 模拟编排执行
    await new Promise((resolve) => setTimeout(resolve, 2000));

    // 模拟执行结果
    testResult.value = {
      success: true,
      executionTime: '2.1s',
      steps: data.nodes.map((node: any) => ({
        id: node.id,
        type: node.type,
        status: 'completed',
        result: `执行${node.data?.title || node.type}成功`,
      })),
      output: {
        message: '编排执行完成',
        data: params,
      },
    };

    message.success('编排执行成功');
    emit('orchestration-tested', testResult.value);
  } catch (error: any) {
    testError.value = error.message || '执行失败';
    message.error('编排执行失败');
  } finally {
    testLoading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  getData: () => {
    return tinyflowInstance?.getData();
  },
});
</script>

<style lang="less" scoped>
.behavior-orchestration-designer {
  height: 100%;
  display: flex;
  flex-direction: column;

  .designer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;

    h3 {
      margin: 0;
      color: #1890ff;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .designer-content {
    flex: 1;
    overflow: hidden;
    background: #fafafa;

    .behavior-workflow-canvas {
      height: 100%;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
    }
  }

  .test-content {
    .test-section {
      margin-bottom: 24px;

      h4 {
        margin-bottom: 12px;
        color: #333;
        font-weight: 500;
      }

      .param-list {
        .param-item {
          display: flex;
          gap: 8px;
          margin-bottom: 8px;
          align-items: center;

          .param-key {
            flex: 1;
          }

          .param-value {
            flex: 1;
          }

          .param-remove {
            flex-shrink: 0;
          }
        }
      }

      .add-param-btn {
        width: 100%;
        margin-top: 8px;
      }

      .result-content {
        min-height: 200px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        padding: 12px;
        background: #fafafa;

        .loading {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #1890ff;
        }

        .error {
          color: #ff4d4f;
        }

        .result-json {
          background: #fff;
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          padding: 12px;
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
          font-size: 12px;
          line-height: 1.5;
          max-height: 300px;
          overflow: auto;
          white-space: pre-wrap;
        }

        .no-result {
          color: #999;
          text-align: center;
          padding: 40px 0;
        }
      }
    }

    .execute-btn {
      width: 100%;
      margin-top: 16px;
    }
  }
}

.tinyflow-logo:after {
  content: 'Behavior Orchestration';
}

// 数据引用选择器样式
:deep(.data-reference-selector) {
  .ant-input {
    font-size: 12px;
  }
}
</style>
